import java.text.SimpleDateFormat

class DateTagLib {

  static final SHORT_DATE = new SimpleDateFormat("dd.MM. - HH:mm")
  static final MEDIUM_DATE = new SimpleDateFormat("dd.MM.yy - HH:mm")
  static final DATE = new SimpleDateFormat("dd.MM.yy")
  static final TIME = new SimpleDateFormat("HH:mm")

  public static String getNiceDate(Date date) {

    def now = new Date()

    def diff = Math.abs(now.getTime() - date.getTime())

    long second = 1000
    long minute = 1000 * 60
    long hour = minute * 60
    long day = hour * 24

    def niceTime = ""

    long calc = 0L;

    calc = Math.floor(diff / day)
    if (calc > 0) {
      niceTime += calc + " day" + (calc > 1 ? "s " : " ")
      diff = diff % day
    }

    calc = Math.floor(diff / hour)
    if (calc > 0) {
      niceTime += calc + " hour" + (calc > 1 ? "s " : " ")
      diff = diff % hour
    }

    calc = Math.floor(diff / minute)
    if (calc > 0) {
      niceTime += calc + " minute" + (calc > 1 ? "s " : " ")
      diff = diff % minute
    }

    if (niceTime.length() == 0) {
      niceTime = "Right now"
    } else {
      niceTime += (date.getTime() > now.getTime()) ? "from now" : "ago"
    }

    return niceTime

  }

  public static String getShortDate(Date date) {
    return "${SHORT_DATE.format(date)}"
  }

  public static String getMediumDate(Date date) {
    return "${MEDIUM_DATE.format(date)}"
  }

  public static String getTime(Date date) {
    return "${TIME.format(date)}"
  }

  public static String getDate(Date date) {
    if (date) {
      return "${DATE.format(date)}"
    } else {
      return ''
    }
  }



  def dateFromNow = {attrs ->

    def date = attrs.date

    out << getNiceDate(date)

  }

  def shortDate = {attrs ->
    def date = attrs.date
    out << getShortDate(date)
  }

  def time = {attrs ->
    def date = attrs.date
    out << getTime(date)
  }

  def date = {attrs ->
    def date = attrs.date
    out << getDate(date)
  }

  def mediumDate = {attrs ->
    def date = attrs.date
    out << getMediumDate(date)
  }


}